package com.app.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.config.RedisService;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class WechatUtil {
    @Resource
    private static RedisService redisService = SpringUtils.getBean(RedisService.class);

    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    //获取手机号
    public static String getMobile(String mobileCode) throws Exception {
        // 获取token
        String token = redisToken();
        // 使用前端code获取手机号码 参数为json格式
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", mobileCode);
        String response = HttpUtil.post(url, JSONUtil.toJsonStr(paramMap));
        log.info("获取用户手机号 响应:{}", response);
        cn.hutool.json.JSONObject entries = JSONUtil.parseObj(response);
        return entries.getJSONObject("phone_info").getStr("phoneNumber");
    }

    //获取Openid
    public static String getOpenid(String code) {
        //请求封装参数
        Map<String, String> map = new HashMap<>();
        map.put("appid", WXConstant.APPID);
        map.put("secret", WXConstant.SECRET);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }

    /**
     * 接口调用凭证 access_token
     */
    public static String postToken(String appId, String appKey) throws Exception {

        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appKey;
        URL url = new URL(requestUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes("");
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in;
        if (requestUrl.contains("nlp")) {
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        } else {
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        }
        StringBuilder result = new StringBuilder();
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result.append(getLine);
        }
        in.close();
        JSONObject jsonObject = JSONObject.parseObject(result.toString());
        return jsonObject.getString("access_token");
    }

    /**
     * redis获取token
     */
    public static String redisToken() throws Exception {
        String accessToken = (String) redisService.getStringKey("suzhouAccessToken");
        if (accessToken == null) {
            accessToken = postToken(WXConstant.APPID, WXConstant.SECRET);
            redisService.setStringKey("access_token", accessToken);
            redisService.setExpire("access_token", 10, TimeUnit.MINUTES);
        }
        return accessToken;
    }
}
